package com.example.a2022110324

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import android.widget.GridView
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private val board = Array(GRID_SIZE) { IntArray(GRID_SIZE) }
    private var currentPlayer = 1

    @SuppressLint("WrongViewCast")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val gridView = findViewById<GridView>(R.id.gridView)
        gridView.adapter = GridAdapter(this)
        gridView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            val row = position / GRID_SIZE
            val col = position % GRID_SIZE
            if (board[row][col] == 0) {  // 检查该位置是否为空
                board[row][col] = currentPlayer
                (view as ImageView).setImageResource(
                    if (currentPlayer == 1) R.drawable.black else R.drawable.white
                )
                if (checkWin(row, col, currentPlayer)) {
                    showWinDialog(currentPlayer)
                } else {
                    currentPlayer = if (currentPlayer == 1) 2 else 1
                }
            }
        }
    }

    private fun checkWin(row: Int, col: Int, player: Int): Boolean {
        return (checkDirection(row, col, 1, 0, player) || // 水平检查
                checkDirection(row, col, 0, 1, player) || // 垂直检查
                checkDirection(row, col, 1, 1, player) || // 主对角线检查
                checkDirection(row, col, 1, -1, player))   // 副对角线检查
    }

    private fun checkDirection(row: Int, col: Int, dx: Int, dy: Int, player: Int): Boolean {
        var count = 1
        var x = row + dx
        var y = col + dy
        // 向一个方向检查
        while (x in 0 until GRID_SIZE && y in 0 until GRID_SIZE && board[x][y] == player) {
            count++
            x += dx
            y += dy
        }
        x = row - dx
        y = col - dy
        // 向另一个方向检查
        while (x in 0 until GRID_SIZE && y in 0 until GRID_SIZE && board[x][y] == player) {
            count++
            x -= dx
            y -= dy
        }
        return count >= 5
    }

    private fun resetBoard() {
        // 重置棋盘
        for (row in 0 until GRID_SIZE) {
            for (col in 0 until GRID_SIZE) {
                board[row][col] = 0  // 清空棋盘数据
            }
        }
        // 通知GridView刷新
        (findViewById<GridView>(R.id.gridView).adapter as GridAdapter).notifyDataSetChanged()
    }

    private fun showWinDialog(winner: Int) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Player $winner Wins!")
            .setMessage("Do you want to play again?")
            .setCancelable(false)
            .setPositiveButton("Yes") { _, _ ->
                resetBoard()
                currentPlayer = 1
            }
            .setNegativeButton("No") { _, _ ->
                Toast.makeText(this, "Game Over", Toast.LENGTH_SHORT).show()
            }
        builder.create().show()
    }

    inner class GridAdapter(private val context: Context) : BaseAdapter() {
        override fun getCount(): Int = GRID_SIZE * GRID_SIZE

        override fun getItem(position: Int): Any? = null

        override fun getItemId(position: Int): Long = position.toLong()

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val imageView = convertView as? ImageView ?: ImageView(context).apply {
                scaleType = ImageView.ScaleType.CENTER_CROP
                layoutParams = ViewGroup.LayoutParams(100, 100)  // 每个格子的大小
            }

            val row = position / GRID_SIZE
            val col = position % GRID_SIZE

            // 根据棋盘的状态设置每个格子的图片
            when (board[row][col]) {
                1 -> imageView.setImageResource(R.drawable.black)  // 黑方棋子
                2 -> imageView.setImageResource(R.drawable.white)  // 白方棋子
                else -> imageView.setImageResource(R.drawable.empty)  // 空格
            }

            return imageView
        }
    }

    companion object {
        private const val GRID_SIZE = 15  // 定义15x15的棋盘
    }
}
